package com.zhongshengnetwork.rightbe;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.app.Fragment;
//import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.dd.CircularProgressButton;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.MyUriUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DeviceUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.HandlerDefine;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LogindbModel;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.game.activity.CancleWordActivity;
import com.zhongshengnetwork.rightbe.game.activity.GameActivity;
import com.zhongshengnetwork.rightbe.game.activity.GameRangeActivity;
import com.zhongshengnetwork.rightbe.game.activity.GuessWordActivity;
import com.zhongshengnetwork.rightbe.game.activity.HeaderWordActivity;
import com.zhongshengnetwork.rightbe.game.activity.LinkWordActivity;
import com.zhongshengnetwork.rightbe.game.activity.LogicalSubjectActivity;
import com.zhongshengnetwork.rightbe.game.activity.PicGameActivity;
import com.zhongshengnetwork.rightbe.game.activity.PrePKActivity;
import com.zhongshengnetwork.rightbe.game.activity.SubjectWordActivity;
import com.zhongshengnetwork.rightbe.game.view.PKMenuPopWindow;
import com.zhongshengnetwork.rightbe.gsonmodel.AdvModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.HomeDataModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKMenuModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.my.activity.MyCenterActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imlib.RongIMClient;
import pl.droidsonroids.gif.GifImageView;

import static android.app.Activity.RESULT_OK;

/**
 * Created by luojingxing on 2018/6/11.
 */

public class GameFragment  extends BaseAnalyticsFragment {

    private final static String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe";//Constant.HOST+"downapp.do?";
    private final static String content = "王者对战，好玩又益智，赶紧来体验吧~";
    private List<String> list;
    private List<String> menuList;
    private PublishSelectPicPopupWindow menuWindow;

    public PKMenuPopWindow pkMenuPopWindow;

    private CircularProgressButton pk_bg;
    private Bitmap placeImg = null;
    private GifImageView home_bg_img;

    private HorizontalScrollView pk_menu_all;
    private LinearLayout game_down_menu;
    private RelativeLayout gamemenu_down_1;
    private ImageView gamemenu_down_img_1;
    private ImageView gamemenu_down_icon_1;
    private TextView gamemenu_down_text_1;
    private TextView gamemenu_down_adv_1;
    private RelativeLayout gamemenu_down_2;
    private ImageView gamemenu_down_img_2;
    private ImageView gamemenu_down_icon_2;
    private TextView gamemenu_down_text_2;
    private TextView gamemenu_down_adv_2;
    private RelativeLayout gamemenu_down_3;
    private ImageView gamemenu_down_img_3;
    private ImageView gamemenu_down_icon_3;
    private TextView gamemenu_down_text_3;
    private TextView gamemenu_down_adv_3;
    private RelativeLayout gamemenu_down_4;
    private ImageView gamemenu_down_img_4;
    private ImageView gamemenu_down_icon_4;
    private TextView gamemenu_down_text_4;
    private TextView gamemenu_down_adv_4;

    private LinearLayout game_up_menu;
    private RelativeLayout gamemenu_up_1;
    private ImageView gamemenu_up_img_1;
    private ImageView gamemenu_up_icon_1;
    private TextView gamemenu_up_text_1;
    private TextView gamemenu_up_adv_1;
    private RelativeLayout gamemenu_up_2;
    private ImageView gamemenu_up_img_2;
    private ImageView gamemenu_up_icon_2;
    private TextView gamemenu_up_text_2;
    private TextView gamemenu_up_adv_2;
    private RelativeLayout gamemenu_up_3;
    private ImageView gamemenu_up_img_3;
    private ImageView gamemenu_up_icon_3;
    private TextView gamemenu_up_text_3;
    private TextView gamemenu_up_adv_3;
    private RelativeLayout gamemenu_up_4;
    private ImageView gamemenu_up_img_4;
    private ImageView gamemenu_up_icon_4;
    private TextView gamemenu_up_text_4;
    private TextView gamemenu_up_adv_4;
    private List<HomeDataModel> homeList = null;
    private List<HomeDataModel> moreList = null;
    private Handler handler = new Handler();
    private boolean isGetMenu = false;
    private AVLoadingIndicatorView avi;
    private boolean isAutoLogin = false;
    private RelativeLayout pk_function_layout;
    private View rootView;//缓存Fragment view
    private ReceiveBroadCast receiveBroadCast;
    private Context broadContext;

    //QQ分享
    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Log.e("TAG","分享成功aaa");
            getShareGold();
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    class ReceiveBroadCast extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            //得到广播中得到的数据
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Share_Result)) {
                //if (MyActivityManager.getInstance().getCurrentActivity() instanceof MainActivity)
                {
                    //微信分享成功
                    getShareGold();
                }

            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        /*
        broadContext = context;
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastDefine.WX_Share_Result);    //只有持有相同的action的接受者才能接收此广播
        if (broadContext != null && receiveBroadCast != null){
            Intent intent = new Intent();
            intent.setAction(BroadcastDefine.WX_Share_Result);
            PackageManager pm = broadContext.getPackageManager();
            List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
            if(resolveInfos != null && !resolveInfos.isEmpty()){
                //查询到相应的BroadcastReceiver
                broadContext.unregisterReceiver(receiveBroadCast);
            }
        }
        context.registerReceiver(receiveBroadCast, filter);
        */
    }
    /**
     *注销广播
     * */
    @Override
    public void onDestroyView() {
        /*
        if (broadContext != null && receiveBroadCast != null){
            Intent intent = new Intent();
            intent.setAction(BroadcastDefine.WX_Share_Result);
            PackageManager pm = broadContext.getPackageManager();
            List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
            if(resolveInfos != null && !resolveInfos.isEmpty()){
                //查询到相应的BroadcastReceiver
                broadContext.unregisterReceiver(receiveBroadCast);
            }
        }
        */
        super.onDestroyView();
    }

    private void getShareGold(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+"pkappid"+"/usershare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    new Handler().postDelayed(new Runnable(){
                        public void run() {
                            ToastUtil.show(getActivity(),commonModel.getMsg());
                        }
                    }, 10);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG","传递onActivityResult");
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE || requestCode == Constants.REQUEST_OLD_SHARE) {
            //Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
            Tencent.handleResultData(data, mIUiListener);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null){
            rootView=inflater.inflate(R.layout.game_fragment_layout,container, false);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        initMenu();
        goToUrl();
        list = new ArrayList<String>();
        list.add("分享给微信好友");
        list.add("分享到微信朋友圈");
        list.add("分享给QQ好友");
        list.add("分享到QQ空间");
        list.add("每日签到");
        //list.add("取消");
        menuList = new ArrayList<>();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String filePath = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.HomeImgPath,"");
                if (!CommonUtils.isEmpty(filePath)){
                    Log.e("TAG","首页图片路径是："+filePath+"\n");
                    boolean status = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.HomeStatus,false);
                    if (AdvertUtils.fileIsExists(filePath) && status == true){
                        home_bg_img.setImageURI(MyUriUtils.getUri(CustomApplication.mContext,filePath));
                    }
                }
            }
        },300);
        return rootView;
    }

    private void goToUrl(){
        if (getActivity() == null){
            return;
        }
        String url = getActivity().getIntent().getStringExtra(APIKey.urlKey);
        if (!CommonUtils.isEmpty(url)){
            Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
            webIntent.putExtra(APIKey.urlKey, url);
            startActivity(webIntent);
        }
    }

    private void initMenu(){
        pk_bg = (CircularProgressButton)rootView.findViewById(R.id.pk_bg);
        pk_bg.setBackgroundColor(getResources().getColor(R.color.commonColor));
        pk_bg.setStrokeColor(getResources().getColor(R.color.commonColor));
        pk_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickPK(v);
            }
        });

        home_bg_img = (GifImageView) rootView.findViewById(R.id.home_bg_img);
        home_bg_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickBg(v);
            }
        });

        pk_menu_all = (HorizontalScrollView)rootView.findViewById(R.id.pk_menu_all);
        game_down_menu = (LinearLayout)rootView.findViewById(R.id.game_down_menu);
        gamemenu_down_1 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_down_1);
        gamemenu_down_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_down_img_1 = (ImageView)rootView.findViewById(R.id.gamemenu_down_img_1);
        gamemenu_down_icon_1 = (ImageView)rootView.findViewById(R.id.gamemenu_down_icon_1);
        gamemenu_down_text_1 = (TextView)rootView.findViewById(R.id.gamemenu_down_text_1);
        gamemenu_down_adv_1 = (TextView)rootView.findViewById(R.id.gamemenu_down_adv_1);
        gamemenu_down_2 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_down_2);
        gamemenu_down_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_down_img_2 = (ImageView)rootView.findViewById(R.id.gamemenu_down_img_2);
        gamemenu_down_icon_2 = (ImageView)rootView.findViewById(R.id.gamemenu_down_icon_2);
        gamemenu_down_text_2 = (TextView)rootView.findViewById(R.id.gamemenu_down_text_2);
        gamemenu_down_adv_2 = (TextView)rootView.findViewById(R.id.gamemenu_down_adv_2);
        gamemenu_down_3 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_down_3);
        gamemenu_down_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_down_img_3 = (ImageView)rootView.findViewById(R.id.gamemenu_down_img_3);
        gamemenu_down_icon_3 = (ImageView)rootView.findViewById(R.id.gamemenu_down_icon_3);
        gamemenu_down_text_3 = (TextView)rootView.findViewById(R.id.gamemenu_down_text_3);
        gamemenu_down_adv_3 = (TextView)rootView.findViewById(R.id.gamemenu_down_adv_3);
        gamemenu_down_4 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_down_4);
        gamemenu_down_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_down_img_4 = (ImageView)rootView.findViewById(R.id.gamemenu_down_img_4);
        gamemenu_down_icon_4 = (ImageView)rootView.findViewById(R.id.gamemenu_down_icon_4);
        gamemenu_down_text_4 = (TextView)rootView.findViewById(R.id.gamemenu_down_text_4);
        gamemenu_down_adv_4 = (TextView)rootView.findViewById(R.id.gamemenu_down_adv_4);

        game_up_menu = (LinearLayout)rootView.findViewById(R.id.game_up_menu);
        gamemenu_up_1 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_up_1);
        gamemenu_up_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_up_img_1 = (ImageView)rootView.findViewById(R.id.gamemenu_up_img_1);
        gamemenu_up_icon_1 = (ImageView)rootView.findViewById(R.id.gamemenu_up_icon_1);
        gamemenu_up_text_1 = (TextView)rootView.findViewById(R.id.gamemenu_up_text_1);
        gamemenu_up_adv_1 = (TextView)rootView.findViewById(R.id.gamemenu_up_adv_1);
        gamemenu_up_2 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_up_2);
        gamemenu_up_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_up_img_2 = (ImageView)rootView.findViewById(R.id.gamemenu_up_img_2);
        gamemenu_up_icon_2 = (ImageView)rootView.findViewById(R.id.gamemenu_up_icon_2);
        gamemenu_up_text_2 = (TextView)rootView.findViewById(R.id.gamemenu_up_text_2);
        gamemenu_up_adv_2 = (TextView)rootView.findViewById(R.id.gamemenu_up_adv_2);
        gamemenu_up_3 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_up_3);
        gamemenu_up_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_up_img_3 = (ImageView)rootView.findViewById(R.id.gamemenu_up_img_3);
        gamemenu_up_icon_3 = (ImageView)rootView.findViewById(R.id.gamemenu_up_icon_3);
        gamemenu_up_text_3 = (TextView)rootView.findViewById(R.id.gamemenu_up_text_3);
        gamemenu_up_adv_3 = (TextView)rootView.findViewById(R.id.gamemenu_up_adv_3);
        gamemenu_up_4 = (RelativeLayout)rootView.findViewById(R.id.gamemenu_up_4);
        gamemenu_up_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickMenu(v);
            }
        });
        gamemenu_up_img_4 = (ImageView)rootView.findViewById(R.id.gamemenu_up_img_4);
        gamemenu_up_icon_4 = (ImageView)rootView.findViewById(R.id.gamemenu_up_icon_4);
        gamemenu_up_text_4 = (TextView)rootView.findViewById(R.id.gamemenu_up_text_4);
        gamemenu_up_adv_4 = (TextView)rootView.findViewById(R.id.gamemenu_up_adv_4);
        avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
        pk_function_layout = (RelativeLayout) rootView.findViewById(R.id.pk_function_layout);

        new Thread() {
            @Override
            public void run() {
                super.run();
                String homeData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.HomeData,"");
                if (!CommonUtils.isEmpty(homeData)){
                    setHomeView(homeData);
                }else {
                    final HashMap<String, String> map = new HashMap<String, String>();
                    if (CommonUtils.isLogin() == true){
                        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                    }else {
                        map.put(APIKey.tokenKey, "1");
                    }
                    String url = "miniapp/appid/getsubjectname.do";
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            final CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.HomeData,data);
                                setHomeView(data);
                            }
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
                }

            }
        }.start();

        autoLogin();

    }

    private void autoLogin(){
        if(CustomApplication.loginModel != null && !CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
            return;
        }
        if (isAutoLogin == true){
            return;
        }
        isAutoLogin = true;

        new Thread() {
            @Override
            public void run() {
                super.run();
                String mobileid = DeviceUtils.getDeviceID();
                if (mobileid == null || mobileid.length() == 0){
                    return;
                }
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put("mobileid", mobileid);
                String url = "api/user/autologin.do";
                Log.e("TAG","重新获取token\n");
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        isAutoLogin = false;
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final LogindbModel model = GsonTools.getThirdLogindbModel(data);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (CustomApplication.loginModel == null){
                                        CustomApplication.loginModel = new LogindbModel();
                                        CustomApplication.loginModel.setUid("1");//默认用户id
                                    }
                                    System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                                    CustomApplication.loginModel.setRctoken(model.getRctoken());
                                    CustomApplication.loginModel.setToken(model.getToken());
                                    CustomApplication.isAutoLogin = true;
                                    Log.e("TAG","获取的token="+CustomApplication.loginModel.getToken());
                                    CustomApplication.loginModel.setExpires(model.getExpires());
                                    CustomApplication.loginModel.setUid(model.getUid());
                                    CustomApplication.loginModel.setHeader(model.getHeader());
                                    CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                                    CustomApplication.loginModel.setBackground(model.getBackground());
                                    CustomApplication.loginModel.setNickname(model.getNickname());
                                    CustomApplication.loginModel.setSex(model.getSex());
                                    CustomApplication.loginModel.setSignature(model.getSignature());
                                    CustomApplication.loginModel.setLocation(model.getLocation());
                                    CustomApplication.loginModel.setUserauth(model.getUserauth());
                                    CustomApplication.loginModel.setPayauth(model.getPayauth());
                                    CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                                    CustomApplication.loginModel.setMobile(model.getMobile());
                                    CustomApplication.loginModel.setNeed(model.getNeed());
                                    LogindbService.deleteLoginModel();
                                    LogindbService.saveOrUpdateLogindbMode(CustomApplication.loginModel);
                                }
                            },10);

                        }
                    }

                    @Override
                    public void onError(String msg) {
                        isAutoLogin = false;
                    }
                });
            }
        }.start();

    }

    private void setHomeView(final String data){


        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                avi.hide();
                if (!CommonUtils.isEmpty(data)){
                    List<HomeDataModel> ll = GsonTools.getHomeDataModel(data);
                    if (ll != null && ll.size() > 0){
                        if (moreList == null){
                            moreList = new ArrayList<HomeDataModel>();
                        }else {
                            moreList.clear();
                        }
                        if (homeList == null){
                            homeList = new ArrayList<HomeDataModel>();
                        }else {
                            homeList.clear();
                        }
                        for (int i = 0; i < ll.size(); i++){
                            HomeDataModel homeDataModel = ll.get(i);
                            if (i < 8){
                                if (i == 7 && ll.size() > 8){
                                    HomeDataModel model = new HomeDataModel();
                                    model.setName(homeDataModel.getName());
                                    model.setAppid(homeDataModel.getAppid());
                                    model.setIcon(homeDataModel.getIcon());
                                    model.setBgcolor(homeDataModel.getBgcolor());
                                    model.setBgurl(homeDataModel.getBgurl());
                                    model.setContenturl(homeDataModel.getContenturl());
                                    model.setType(homeDataModel.getType());
                                    moreList.add(model);
                                    homeDataModel.setAppid("moreappid");
                                    homeDataModel.setName("更多答题");
                                    homeDataModel.setIcon("");
                                }
                                homeList.add(homeDataModel);
                            }else {
                                moreList.add(homeDataModel);
                            }
                        }
                        if (homeList.size() > 6){
                            for (int i = 0; i < homeList.size();i++){
                                HomeDataModel m = homeList.get(i);
                                if (i == 0){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_1.setVisibility(View.GONE);
                                        gamemenu_up_text_1.setVisibility(View.GONE);
                                        gamemenu_up_adv_1.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_1);
                                    }else {
                                        gamemenu_up_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_1.setVisibility(View.GONE);
                                        gamemenu_up_img_1.setVisibility(View.GONE);
                                        gamemenu_up_text_1.setText(m.getName());
                                        gamemenu_up_icon_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_1);
                                        }
                                    }
                                }else if (i == 1){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_2.setVisibility(View.GONE);
                                        gamemenu_up_text_2.setVisibility(View.GONE);
                                        gamemenu_up_adv_2.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_2);
                                    }else {
                                        gamemenu_up_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_2.setVisibility(View.GONE);
                                        gamemenu_up_img_2.setVisibility(View.GONE);
                                        gamemenu_up_text_2.setText(m.getName());
                                        gamemenu_up_icon_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_2);
                                        }
                                    }
                                }else if (i == 2){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_3.setVisibility(View.GONE);
                                        gamemenu_up_text_3.setVisibility(View.GONE);
                                        gamemenu_up_adv_3.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_3);
                                    }else {
                                        gamemenu_up_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_3.setVisibility(View.GONE);
                                        gamemenu_up_img_3.setVisibility(View.GONE);
                                        gamemenu_up_text_3.setText(m.getName());
                                        gamemenu_up_icon_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_3);
                                        }
                                    }
                                }else if (i == 3){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_4.setVisibility(View.GONE);
                                        gamemenu_up_text_4.setVisibility(View.GONE);
                                        gamemenu_up_adv_4.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_4);
                                    }else {
                                        gamemenu_up_4.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_4.setVisibility(View.GONE);
                                        gamemenu_up_img_4.setVisibility(View.GONE);
                                        gamemenu_up_text_4.setText(m.getName());
                                        gamemenu_up_icon_4.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_4);
                                        }
                                    }
                                }else if (i == 4){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_1.setVisibility(View.GONE);
                                        gamemenu_down_text_1.setVisibility(View.GONE);
                                        gamemenu_down_adv_1.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_1);
                                    }else {
                                        gamemenu_down_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_1.setVisibility(View.GONE);
                                        gamemenu_down_img_1.setVisibility(View.GONE);
                                        gamemenu_down_text_1.setText(m.getName());
                                        gamemenu_down_icon_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_1);
                                        }
                                    }
                                }else if (i == 5){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_2.setVisibility(View.GONE);
                                        gamemenu_down_text_2.setVisibility(View.GONE);
                                        gamemenu_down_adv_2.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_2);
                                    }else {
                                        gamemenu_down_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_2.setVisibility(View.GONE);
                                        gamemenu_down_img_2.setVisibility(View.GONE);
                                        gamemenu_down_text_2.setText(m.getName());
                                        gamemenu_down_icon_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_2);
                                        }
                                    }
                                }else if (i == 6){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_3.setVisibility(View.GONE);
                                        gamemenu_down_text_3.setVisibility(View.GONE);
                                        gamemenu_down_adv_3.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_3);
                                    }else {
                                        gamemenu_down_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_3.setVisibility(View.GONE);
                                        gamemenu_down_img_3.setVisibility(View.GONE);
                                        gamemenu_down_text_3.setText(m.getName());
                                        gamemenu_down_icon_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_3);
                                        }
                                    }
                                }else if (i == 7){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_4.setVisibility(View.GONE);
                                        gamemenu_down_text_4.setVisibility(View.GONE);
                                        gamemenu_down_adv_4.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_4);
                                    }else {
                                        gamemenu_down_4.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_4.setVisibility(View.GONE);
                                        gamemenu_down_img_4.setVisibility(View.GONE);
                                        gamemenu_down_text_4.setText(m.getName());
                                        gamemenu_down_icon_4.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_4);
                                        }
                                    }
                                }
                            }
                            if (homeList.size() == 7){
                                //gamemenu_down_1.setVisibility(View.INVISIBLE);
                                //gamemenu_down_2.setVisibility(View.INVISIBLE);
                                //gamemenu_down_3.setVisibility(View.INVISIBLE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                //gamemenu_up_4.setVisibility(View.INVISIBLE);
                            }
                        }else {
                            for (int i = 0; i < homeList.size();i++){
                                HomeDataModel m = homeList.get(i);
                                if (i == 0){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_1.setVisibility(View.GONE);
                                        gamemenu_up_text_1.setVisibility(View.GONE);
                                        gamemenu_up_adv_1.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_1);
                                    }else {
                                        gamemenu_up_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_1.setVisibility(View.GONE);
                                        gamemenu_up_img_1.setVisibility(View.GONE);
                                        gamemenu_up_text_1.setText(m.getName());
                                        gamemenu_up_icon_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_1);
                                        }
                                    }
                                }else if (i == 1){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_2.setVisibility(View.GONE);
                                        gamemenu_up_text_2.setVisibility(View.GONE);
                                        gamemenu_up_adv_2.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_2);
                                    }else {
                                        gamemenu_up_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_2.setVisibility(View.GONE);
                                        gamemenu_up_img_2.setVisibility(View.GONE);
                                        gamemenu_up_text_2.setText(m.getName());
                                        gamemenu_up_icon_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_2);
                                        }
                                    }
                                }else if (i == 2){
                                    if (m.getName().equals("广告")){
                                        gamemenu_up_icon_3.setVisibility(View.GONE);
                                        gamemenu_up_text_3.setVisibility(View.GONE);
                                        gamemenu_up_adv_3.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_img_3);
                                    }else {
                                        gamemenu_up_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_up_adv_3.setVisibility(View.GONE);
                                        gamemenu_up_img_3.setVisibility(View.GONE);
                                        gamemenu_up_text_3.setText(m.getName());
                                        gamemenu_up_icon_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_up_icon_3);
                                        }
                                    }
                                }else if (i == 3){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_1.setVisibility(View.GONE);
                                        gamemenu_down_text_1.setVisibility(View.GONE);
                                        gamemenu_down_adv_1.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_1);
                                    }else {
                                        gamemenu_down_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_1.setVisibility(View.GONE);
                                        gamemenu_down_img_1.setVisibility(View.GONE);
                                        gamemenu_down_text_1.setText(m.getName());
                                        gamemenu_down_icon_1.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_1);
                                        }
                                    }
                                }else if (i == 4){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_2.setVisibility(View.GONE);
                                        gamemenu_down_text_2.setVisibility(View.GONE);
                                        gamemenu_down_adv_2.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_2);
                                    }else {
                                        gamemenu_down_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_2.setVisibility(View.GONE);
                                        gamemenu_down_img_2.setVisibility(View.GONE);
                                        gamemenu_down_text_2.setText(m.getName());
                                        gamemenu_down_icon_2.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_2);
                                        }
                                    }
                                }else if (i == 5){
                                    if (m.getName().equals("广告")){
                                        gamemenu_down_icon_3.setVisibility(View.GONE);
                                        gamemenu_down_text_3.setVisibility(View.GONE);
                                        gamemenu_down_adv_3.setText(m.getName());
                                        Glide.with(getActivity()).load(m.getBgurl()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_img_3);
                                    }else {
                                        gamemenu_down_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        gamemenu_down_adv_3.setVisibility(View.GONE);
                                        gamemenu_down_img_3.setVisibility(View.GONE);
                                        gamemenu_down_text_3.setText(m.getName());
                                        gamemenu_down_icon_3.setBackgroundColor(Color.parseColor("#"+m.getBgcolor()));
                                        if (!CommonUtils.isEmpty(m.getIcon())){
                                            Glide.with(getActivity()).load(m.getIcon()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(gamemenu_down_icon_3);
                                        }
                                    }
                                }
                            }
                            if (homeList.size() == 1){
                                gamemenu_down_1.setVisibility(View.GONE);
                                gamemenu_down_2.setVisibility(View.GONE);
                                gamemenu_down_3.setVisibility(View.GONE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_2.setVisibility(View.GONE);
                                gamemenu_up_3.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 2) {
                                gamemenu_down_1.setVisibility(View.GONE);
                                gamemenu_down_2.setVisibility(View.GONE);
                                gamemenu_down_3.setVisibility(View.GONE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_3.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 3){
                                gamemenu_down_1.setVisibility(View.GONE);
                                gamemenu_down_2.setVisibility(View.GONE);
                                gamemenu_down_3.setVisibility(View.GONE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 4){
                                //gamemenu_down_1.setVisibility(View.INVISIBLE);
                                gamemenu_down_2.setVisibility(View.GONE);
                                gamemenu_down_3.setVisibility(View.GONE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 5){
                                //gamemenu_down_1.setVisibility(View.INVISIBLE);
                                //gamemenu_down_2.setVisibility(View.INVISIBLE);
                                gamemenu_down_3.setVisibility(View.GONE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 6){
                                //gamemenu_down_1.setVisibility(View.INVISIBLE);
                                //gamemenu_down_2.setVisibility(View.INVISIBLE);
                                //gamemenu_down_3.setVisibility(View.INVISIBLE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                gamemenu_up_4.setVisibility(View.GONE);
                            }else if (homeList.size() == 7){
                                //gamemenu_down_1.setVisibility(View.INVISIBLE);
                                //gamemenu_down_2.setVisibility(View.INVISIBLE);
                                //gamemenu_down_3.setVisibility(View.INVISIBLE);
                                gamemenu_down_4.setVisibility(View.GONE);
                                //gamemenu_up_4.setVisibility(View.INVISIBLE);
                            }
                        }
                        pk_menu_all.setVisibility(View.VISIBLE);
                        game_down_menu.setVisibility(View.VISIBLE);
                        game_up_menu.setVisibility(View.VISIBLE);
                    }

                    List<AdvModel> list = GsonTools.getAdvModel(data);
                    if (list != null && list.size() > 0){
                        for (AdvModel model : list){
                            if (model.getType() == 0){//启动广告
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.AdvBgUrl,model.getBgurl());
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.AdvStatus,model.isStatus());
                                if (CommonUtils.isEmpty(model.getContenturl())==false) {
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.AdvContentUrl, model.getContenturl());
                                }
                                loadAdvertImg(model.getBgurl(),AdvertUtils.AdvImgPath);
                            }else if (model.getType() == 1){//首页
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.HomeBgUrl,model.getBgurl());
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.HomeStatus,model.isStatus());
                                if (CommonUtils.isEmpty(model.getContenturl())==false){
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.HomeContentUrl,model.getContenturl());
                                }
                                loadAdvertImg(model.getBgurl(),AdvertUtils.HomeImgPath);
                            }
                        }
                    }
                    animationOut();
                }
            }
        }, 10);//3秒后执行Runnable中的run方法

    }

    public void onClickMenu(View view){
        Log.e("TAG","点击了菜单\n");
        HomeDataModel model = null;
        switch (view.getId()){
            case R.id.gamemenu_down_1:
                if (homeList.size()>6){
                    model = homeList.get(4);
                }else {
                    model = homeList.get(3);
                }
                break;
            case R.id.gamemenu_down_2:
                if (homeList.size()>6){
                    model = homeList.get(5);
                }else {
                    model = homeList.get(4);
                }
                break;
            case R.id.gamemenu_down_3:
                if (homeList.size()>6){
                    model = homeList.get(6);
                }else {
                    model = homeList.get(5);
                }
                break;
            case R.id.gamemenu_down_4:
                if (homeList.size()>6){
                    model = homeList.get(7);
                }else {
                    model = homeList.get(6);
                }
                break;
            case R.id.gamemenu_up_1:
                model = homeList.get(0);
                break;
            case R.id.gamemenu_up_2:
                model = homeList.get(1);
                break;
            case R.id.gamemenu_up_3:
                model = homeList.get(2);
                break;
            case R.id.gamemenu_up_4:
                model = homeList.get(3);
                break;
        }
        dealWithMenu(model);
    }

    public void dealWithMenu(HomeDataModel model){
        if (getActivity() == null){
            return;
        }
        if (model != null){
            if (CustomApplication.loginModel == null){
                CustomApplication.loginModel = new LogindbModel();
                CustomApplication.loginModel.setUid("1");//默认用户id
            }
            if (CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
                autoLogin();
                //startActivity(new Intent(getActivity(), LoginActivity.class));
                return;
            }
            if (model.getAppid().equals("appid")){//成语猜猜
                startActivity(new Intent(getActivity(), GuessWordActivity.class));
            }else if (model.getAppid().equals("appidlianlian")){//成语消消
                startActivity(new Intent(getActivity(), CancleWordActivity.class));
            }else if (model.getAppid().equals("linkwordappid")){//成语接龙
                Intent intent = new Intent(getActivity(), LinkWordActivity.class);
                intent.putExtra("model",model);
                startActivity(intent);
            }else if (model.getAppid().equals("smartwordappid")){//智多多
                Intent intent = new Intent(getActivity(), HeaderWordActivity.class);
                intent.putExtra("model",model);
                startActivity(intent);
            }else if (model.getAppid().contains("subject")){//综合题库
                Intent intent = new Intent(getActivity(), SubjectWordActivity.class);
                intent.putExtra("model",model);
                startActivity(intent);
            }else if(model.getAppid().contains("logicalappid") || model.getAppid().contains("selectappid")){
                Intent intent = new Intent(getActivity(), LogicalSubjectActivity.class);
                intent.putExtra("model",model);
                startActivity(intent);
            }else if(model.getAppid().contains("picappid")){
                Intent intent = new Intent(getActivity(), PicGameActivity.class);
                intent.putExtra("model",model);
                startActivity(intent);
            } else if (model.getAppid().contains("moreappid")){
                showMoreMenu();
            }else if (model.getName().equals("广告")){
                Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
                webIntent.putExtra(APIKey.urlKey, model.getContenturl());
                startActivity(webIntent);
            }else {
                ToastUtil.show(getActivity(),"亲，该功能需要升级到最新版本才能体验哦~");
            }
        }
    }

    private void showMoreMenu(){
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (HomeDataModel m : moreList){
            actionSheetDialog.addSheetItem(m.getName(), null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    HomeDataModel model = moreList.get(which-1);
                    dealWithMenu(model);
                }
            });
        }
        actionSheetDialog.show();

    }

    public void onClickBg(View view){
        if (getActivity() == null){
            return;
        }
        Log.e("TAG","点击了首页背景\n");
        boolean status = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.HomeStatus,false);
        if (status == true){
            String url = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.HomeContentUrl,"");
            if (!CommonUtils.isEmpty(url)){
                Log.e("TAG","背景链接是："+url+"" + "\n");
                if (url.contains("appfunction:")){
                    String index = url.substring(url.indexOf(":")+1,url.length());
                    if (homeList != null && homeList.size() > 0){
                        HomeDataModel model = homeList.get(Integer.valueOf(index));
                        dealWithMenu(model);
                    }
                }else {
                    Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, url);
                    startActivity(webIntent);
                }

            }

        }
    }

    public void onClickLogin(View view){
        if (getActivity() == null){
            return;
        }
        if (CustomApplication.loginModel == null){
            CustomApplication.loginModel = new LogindbModel();
            CustomApplication.loginModel.setUid("1");//默认用户id
        }
        if (CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        if (CustomApplication.isAutoLogin == true){
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        startActivity(new Intent(getActivity(), MyCenterActivity.class));
    }

    public void onClickPK(View view){
        Log.e("TAG","点击了PK");
        if (CustomApplication.loginModel == null){
            CustomApplication.loginModel = new LogindbModel();
            CustomApplication.loginModel.setUid("1");//默认用户id
        }
        if (CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        if (CustomApplication.isAutoLogin == true){
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        //startActivity(new Intent(getActivity(), PKMenuActivity.class));
        getMenu(view);
    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl =  params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Log.e("path", path+"\n");
            placeImg = BitmapFactory.decodeFile(path);
        }
    }

    private void getMenu(final View view){
        if (isGetMenu == true){
            return;
        }
        avi.show();
        isGetMenu = true;
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+"pkappid"+"/pkmenu.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","数据="+data+"\n");
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    pkMenuPopWindow = new PKMenuPopWindow(getActivity(),itemsOnClick);
                    pkMenuPopWindow.showMenu(data);
                    pkMenuPopWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
                isGetMenu = false;
                avi.hide();
            }
            @Override
            public void onError(String msg) {
                isGetMenu = false;
                avi.hide();
            }
        });
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            Log.e("TAG","点击了\n");
            PKMenuModel pkMenuModel = null;
            switch (v.getId()) {
                case R.id.pk_menu_pop_startpk:
                    pkMenuModel = pkMenuPopWindow.pkMenuList.get(0);
                    break;
                case R.id.pk_menu_pop_middlepk:
                    pkMenuModel = pkMenuPopWindow.pkMenuList.get(1);
                    break;
                case R.id.pk_menu_pop_highpk:
                    pkMenuModel = pkMenuPopWindow.pkMenuList.get(2);
                    break;
                case R.id.pk_menu_pop_facepk:
                    pkMenuModel = pkMenuPopWindow.pkMenuList.get(3);
                    break;
                case R.id.pk_menu_pop_rangepk:
                    pkMenuModel = pkMenuPopWindow.pkMenuList.get(4);
                    break;
                case R.id.getgold:
                    pkMenuPopWindow.dismiss();
                    Log.e("TAG","点击了分享\n");
                    share(v);
                    break;
                case R.id.pk_menu_pop_close:
                    pkMenuPopWindow.dismiss();
                    break;
                default:
                    break;
            }
            if (pkMenuModel != null){
                if (pkMenuModel.getType() == 4){
                    Intent intent = new Intent(getActivity(),GameRangeActivity.class);
                    intent.putExtra("appid","pkappid");
                    startActivity(intent);
                }else if (pkMenuModel.getType() >= 1 && pkMenuModel.getType() <= 3){
                    if (pkMenuModel.isStatus() == false){
                        return;
                    }
                    if (pkMenuModel.getGoldcount() > pkMenuPopWindow.pkUserModel.getGoldcount()){
                        ToastUtil.show(getActivity(),"亲，你金币不足哦");
                        return;
                    }
                    Intent intent = new Intent(getActivity(), PrePKActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("pkuser", pkMenuPopWindow.pkUserModel);//序列化
                    intent.putExtras(bundle);//发送数据
                    intent.putExtra("fee",pkMenuModel.getGoldcount());
                    intent.putExtra("type",pkMenuModel.getType());
                    intent.putExtra("code", CommonUtils.formatString(pkMenuPopWindow.code));
                    startActivity(intent);
                }else if (pkMenuModel.getType() == 0){
                    Log.e("TAG","发送广播~");
                    pkMenuPopWindow.mPKMenuModel = pkMenuModel;
                    Intent mIntent = new Intent(BroadcastDefine.Show_Pay_Action);
                    //发送广播
                    getActivity().sendBroadcast(mIntent);
                    getActivity().setResult(RESULT_OK);
                }
            }

        }
    };
    
    private void signDo(final View v){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+"pkappid"+"/usersign.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {// usersign
            @Override
            public void onSuccess(String data) {
                Log.e("TAG",data);
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(getActivity(),commonModel.getMsg());
                    getMenu(v);
                }else {
                    ToastUtil.show(getActivity(),"你已领取");
                }
            }
            @Override
            public void onError(String msg) {

            }
        });
    }

    private void share(final View v){
        /*
        menuWindow = new PublishSelectPicPopupWindow(getActivity(),itemsOnClickA,list);
        // 显示窗口
        menuWindow.showAtLocation(v,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        */
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : list){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which == 1){
                        //分享给微信好友
                        shareToWX(1,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    }else if (which == 2){
                        //分享到朋友圈
                        shareToWX(0,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    }else if (which == 3){
                        //分享到qq
                        shareToQQ(0,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    }else if (which == 4){
                        //qq空间
                        shareToQQ(1,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    }else if (which == 5){
                        //每日签到
                        signDo(v);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type, String url,String title,String content){
        params = new Bundle();
        if (type == 0){//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(getActivity(), params, mIUiListener);
                }
            });
        }else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add("http://image.daydayrise.net/360@2x.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(getActivity(), params, mIUiListener);
                }
            });
        }

    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClickA = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.first_button:
                    signDo(v);
                    break;
                case R.id.second_button://分享给微信好友
                    shareToWX(1,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    break;
                case R.id.third_button://分享到微信朋友圈
                    shareToWX(0,url,pkMenuPopWindow.pkShareModel.getName(),content);
                    break;
                default:
                    break;
            }

        }
    };

    //分享到微信
    private void shareToWX(int type,String url,String title,String content){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
        msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }


    //下载图片
    private void loadAdvertImg(final String advertUrl, final String key) {
        if (!TextUtils.isEmpty(advertUrl)) {
            final String[] split = advertUrl.split("/");
            File advert = CustomApplication.mContext.getExternalFilesDir("advert");
            //final File file = new File(advert, System.currentTimeMillis() + split[split.length - 1]);
            final File file = new File(advert,  split[split.length - 1]);
            if (AdvertUtils.fileIsExists(file.toString())){
                Log.e("file", "文件存在了："+file.toString());
            }else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("file", "保存路径："+file.toString());
                        try {
                            AdvertUtils.onSaveBitmap(advertUrl, file.toString(),CustomApplication.mContext,key);
                            removeFootList(file.toString(),key);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }

        } else {
            // 获取服务器路径为空时，保存空本地路径，则不显示广告图
            removeFootList("",AdvertUtils.AdvImgPath);
        }

    }

    private void removeFootList(String filePath, String key) {
        String oldFilePath = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(key,"");
        if (!CommonUtils.isEmpty(oldFilePath) && !oldFilePath.equals(filePath)){
            if (AdvertUtils.fileIsExists(oldFilePath)) {
                File f = new File(oldFilePath);
                f.delete();
            }
        }
    }

    private void animationOut(){
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pushfromdown);
        pk_function_layout.startAnimation(animation);
        animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pushfromleft);
        pk_menu_all.startAnimation(animation);
    }

}
